<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #parent{
            width:540px;
            height: 215px;
            position: relative;
            border:1px solid #000;
        }
        #parent>img{
            width:500px;
            padding: 20px;
        }
        #fade{
            width: 540px;
            height: 215px;
            position: absolute;
            left: 0px;
            top:0px;
            background: #4a4266;
            opacity: 0.4;
        }
    </style>
</head>
<body>
    <div id="parent">
        <img src="images/01.jpg" alt="">
        <div id="fade"></div>
    </div>
    <script>
        var parent = document.getElementById("parent");
        var fade = document.getElementById("fade");
        var opacity = getComputedStyle(fade).opacity*100;
        var timer;

        //  未封装 
        // parent.onmouseover = function(){
        //     clearInterval(timer);
        //     //如果不清除则鼠标移上几次就会增加几个定时器，每个定时器执行下面代码，透明度加快
        //     timer = setInterval(function(){
        //         if(opacity == 70){
        //             clearInterval(timer);
        //             //停止继续累加透明度
        //         }    
        //         else{
        //             opacity += 2;
        //             fade.style.opacity = opacity/100;
        //             console.log(opacity);
        //         }
        //     },100)
        // }    
        
        // parent.onmouseout = function(){
        //     clearInterval(timer);
        //     timer = setInterval(function(){
        //         if(opacity == 40){
        //             clearInterval(timer);
        //         }
        //         else{
        //             opacity -= 2;
        //             fade.style.opacity = opacity/100;
        //         }
        //     },100)
        // }

        //封装函数
        parent.onmouseover = function(){
            opacity_change(90,2);
        }
        parent.onmouseout = function(){
            opacity_change(40,-2);
        }
        function opacity_change(reach,add){
            clearInterval(timer);
            timer = setInterval(function(){
                if(opacity == reach){
                    clearInterval(timer);
                }
                else{
                    opacity += add;
                    console.log(opacity/100);
                    fade.style.opacity = opacity/100;
                }
            },100)
        }
    </script>
</body>
</html>